const moment = require('moment');
const errors = require('error');
const { BreathLog, Device, Sequelize } = require('dao');
const utils = require('lib/utils');

const step = 50; //50ms绘图一次
const stepNum = 3; //每step发送的点数
const rate = 5; //5s上传一次

function* addBreathLog(startTime, volumes = [], deviceId) {
	console.log('----------startTime--------', startTime)
	if (!deviceId) errors.throwLackParameters('deviceId=', deviceId);

	volumesCount = volumes.length;
	// volumes = JSON.stringify(volumes);
	startTime = new Date(startTime);
	let start = moment(startTime).valueOf();
	let end = moment(startTime).add(rate, 'seconds').valueOf();

	let log = yield BreathLog.findOne({
		where: {
			deviceId,
			startTime: {
				[Sequelize.Op.and]: {
					[Sequelize.Op.gte]: start,
					[Sequelize.Op.lte]: end
				}
			}
		}
	})

	if (log) errors.throwTimePeriodDataIsExist();

	//分割为1s数据
	let breathLogs = [];
	let secondCount = (1000 / step) * stepNum; //每秒数据量
	console.log('-----------secondCount---------', secondCount, '-------volumesCount-----', volumesCount)
	for (let i = 0; i < rate; i++) {
		let secondStart = moment(startTime).add(i, 'seconds').valueOf();
		let secondEnd = moment(startTime).add(i + 1, 'seconds').valueOf();
		let index = i * secondCount;
		let secondVolumes = volumes.slice(index, index + secondCount);;
		breathLogs.push({ volumes: JSON.stringify(secondVolumes), startTime: secondStart, endTime: secondEnd, deviceId });
		// yield BreathLog.create({ volumes: JSON.stringify(secondVolumes), startTime: secondStart, endTime: secondEnd })
	}

	yield BreathLog.bulkCreate(breathLogs)
}

function* getBreathLog(startTime = moment(0), endTime = moment(), deviceId) {
	if (!deviceId) errors.throwLackParameters();

	startTime = new Date(+startTime);
	endTime = new Date(+endTime);

	let logs = yield BreathLog.findAll({
		where: {
			deviceId,
			startTime: {
				[Sequelize.Op.gte]: startTime
			},
			endTime: {
				[Sequelize.Op.lte]: endTime
			}
		},
		order: [
			['startTime', 'asc']
		],
		raw: true
	})

	// [{startTime,endTime,data},...]
	let pre;
	let result = [];

	//连续时间
	logs.forEach((log) => {
		if (pre) {
			let pEnd = moment(pre.endTime);
			let nStart = moment(log.startTime);
			if (pEnd.valueOf() < nStart.valueOf()) {
				//填补时间
				let dataNum = nStart.diff(pEnd, 'milliseconds') / step;
				let datas = formatLogs({ startTime: pEnd, volumes: Array(dataNum).fill(0) })
				result = result.concat(datas);
			}
		}

		let datas = formatLogs({ startTime: log.startTime, volumes: JSON.parse(log.volumes) })
		// console.log(datas)
		result = result.concat(datas);
		pre = log;
	})


	//格式化数组
	function formatLogs({ startTime, volumes }) {
		let datas = [];
		let time = moment(startTime);
		for (let v of volumes) {
			datas.push({
				name: time.format('YYYY-MM-DD hh:mm:ss:SSS'),
				value: v
			})
			time = time.add(1 * step, 'milliseconds') //next time
		}
		return datas;
	}

	return result;
}


function* addDevice(name, deviceId) {
	yield Device.create({ name, deviceId })
}

function* getDevices(page = 1, limit = 20) {
	let result = yield utils.pagenation(Device, page, limit);
	return result;
}

function* deleteDevice(id) {
	yield Device.destroy({ where: { id } });
}

module.exports = {
	addBreathLog,
	getBreathLog,
	addDevice,
	getDevices,
	deleteDevice
}